<?php

namespace App\Library;

/**
 * AES加解密算法
 * aes 128位 cbc 算法
 * Class EncryptDecrypt
 * @package
 */
class EncryptDecrypt
{
    /**
     * @param string $s_src 加密源
     * @param string $s_key 秘钥
     * @param string $iv 向量
     * @return string
     *
     * @author
     */
    public static function encrypt($s_src, $s_key, string $iv)
    {

        //检查s_src与s_key参数
        if (empty($s_key) || strlen($s_key) != 16) {
            return '';
        }
        // openssl
        return base64_encode(openssl_encrypt(self::ZeroPadding($s_src), 'AES-128-CBC', $s_key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv));
    }

    /**
     * 数据解密
     * @param string $s_src 解密内容
     * @param string $s_key 秘钥
     * @param string $iv_str 向量
     * @return string
     *
     * @author
     */
    public static function decrypt($s_src, $s_key, $iv_str)
    {
        //去掉转义符
        $s_src = str_replace(PHP_EOL, '', $s_src);
        // 解密
        $decrypt = self::ZeroUnPadding(openssl_decrypt(base64_decode($s_src), 'AES-128-CBC', $s_key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv_str));
        // 去除转义字符
        $decrypt = str_replace(PHP_EOL, '', $decrypt);
        return $decrypt;
    }


    public static function ZeroPadding($s_src, $block = 16)
    {
        //Padding
        //Compute how many characters need to pad
        $pad = $block - (strlen($s_src) % $block);
        //After pad, the str length must be equal to block or its integer multiples
        $s_src .= str_repeat(chr($pad), $pad);

        return $s_src;
    }

    public static function ZeroUnPadding($str)
    {
        $pad = ord(substr($str, -1, 1));
        return substr($str, 0, strlen($str) - $pad);
    }

    /**
     * 数据加密
     * @param $operatorID
     * @param $params
     * @return array
     */
    public static function DataEn($operatorID,$params)
    {
        $ymd = date('YmdHis');
        $priv = config('priv.' . "20228888");
        $data = EncryptDecrypt::encrypt(json_encode($params), $priv['DataSecret'], $priv['DataSecretIV']);
        //签名
        $seq = '0001';
        $sign_str = $operatorID . $data . $ymd . $seq;
        $sig = HMACMD5::generate($priv['SigSecret'], $sign_str);
        //请求体
        return [
            'OperatorID' => "20228888",
            'Data' => $data,
            'TimeStamp' => $ymd,
            'Seq' => $seq,
            'Sig' => $sig
        ];
    }

}
